<template>
  <div class="calendar-card" v-if="isShowRef">
    <el-calendar class="custom-calendar" ref="calendar" v-model="selectDateRef">
      <template #header="{ date }">
        <span style="font-size: 13px"
          >{{ date }} - <headerRender :date="date"
        /></span>
        <el-button-group>
          <el-button size="small" @click="selectDate('prev-month')">
            上月
          </el-button>
          <el-button size="small" @click="selectDate('today')">今天</el-button>
          <el-button size="small" @click="selectDate('next-month')">
            下月
          </el-button>
        </el-button-group>
      </template>
      <template #date-cell="{ data }">
        <calendarRender :data="data" />
      </template>
    </el-calendar>
  </div>
</template>

<script setup>
import { h, onMounted, onActivated, ref, nextTick } from 'vue';
// 日历显示农历
import converter from 'js-calendar-converter';
import moment from 'moment';

import { getYearAllDaysWork } from './fetchTeamRest.js';
import { getHolidayApi } from '../../apis/weatherApi';

const calendar = ref();
const selectDateRef = ref(new Date());
const workRredayObjRef = ref(null);
const isShowRef = ref(false);
const nowDateRef = ref();

const selectDate = (val) => {
  if (!calendar.value) return;
  calendar.value.selectDate(val);
};

const calendarRender = ({ data }) => {
  const [y, m, d] = data.day.split('-');
  /**
   * lunarFestival 农历节日
   * festival 活动节日
   * Term 24节气
   * IMonthCn 农历月份
   * Animal 农历年（12生肖年）
   * IDayCn 农历日期
   */
  let { IDayCn, IMonthCn, festival, Animal, lunarFestival, Term } =
    converter.solar2lunar(y, m, d);
  const item = workRredayObjRef.value?.[data.day] || {};

  // 农历初一、节假日 ：文字选择样式处理
  let innerText = '';
  let styles = null;
  if (IDayCn === '初一') {
    innerText = IMonthCn;
    styles = {
      color: 'blue',
      // opacity: 0.8,
      fontWeight: '500',
    };
  } else if (lunarFestival) {
    innerText = lunarFestival;
  } else if (festival) {
    innerText = festival;
  } else if (Term) {
    innerText = Term;
  } else {
    innerText = IDayCn;
    styles = { opacity: 0.5 };
  }

  const workRredayText = workRredayTextFun(item);
  innerText = innerText + workRredayText;

  return h('p', { class: 'dayItem' }, [
    h(
      'span',
      { style: { fontWeight: '500', color: IDayCn === '初一' ? 'blue' : '' } },
      d
    ),
    renderHFun(innerText, styles),
  ]);
};
const renderHFun = (innerText, style = null) => {
  return h(
    'span',
    { class: 'dayCn', style: style || { color: 'red', opacity: 0.8 } },
    innerText
  );
};
const workRredayTextFun = (item = {}) => {
  let text = '';
  if (item.isWork) {
    text = '(班)';
  } else if (item.isRreeday) {
    text = '(休)';
  }
  return text;
};

const headerRender = ({ date }) => {
  const [y, m, d] = moment(selectDateRef.value).format('YYYY-MM-DD').split('-');
  const { Animal } = converter.solar2lunar(y, m, d);
  return h('span', Animal);
};

// 获取农历（节气、班、休）
const queryChineseCalendar = async () => {
  const year = new Date().getFullYear();
  // 获取班、休
  try {
    const { data } = await getHolidayApi(year);
    if (data) {
      const data2 = await getYearAllDaysWork(data);
      workRredayObjRef.value = data2;
    }
  } finally {
    isShowRef.value = true;
  }
};

onMounted(() => {
  queryChineseCalendar();
  // 初始化第一缓存的日期
  nowDateRef.value = moment().format('YYYY-MM-DD');
});
onActivated(() => {
  // 因为使用了keep-alive 导致隔天之后，日期控件没有重载。获取今天方法失效。
  // 此处判断momented 记录的日期 是否等于 当前最新日期
  // 不相等则刷新dom
  const newDate = moment().format('YYYY-MM-DD');
  if (nowDateRef.value === newDate) return;
    isShowRef.value = false;
    queryChineseCalendar();
});
</script>

<style scoped>
/* css 带 --system 变量去 App.vue中寻找  */
.custom-calendar {
  --td-border-radius: 22px;
  height: 319px;
}
/* 自定义日历样式 */
.custom-calendar >>> .el-calendar__header {
  /* background-color: #f0f0f0; */
  color: #606266;
  padding: 10px 20px 4px 20px;
}
.custom-calendar >>> .el-calendar__body {
  padding-bottom: 20px;
}

.custom-calendar >>> .el-calendar-table thead th {
  padding: 6px 0;
}
.custom-calendar >>> .el-calendar-table .el-calendar-day {
  height: 38px;
  line-height: 12px;
  padding: 2px 5px;
  display: flex;
  align-items: center;
  justify-content: center;
}
.custom-calendar >>> .el-calendar-table td.is-today {
  font-weight: bold;
  color: var(--system-primary-color);
  border-radius: var(--td-border-radius);
  background-color: var(--system-active-bg-color);
}
.custom-calendar >>> .el-calendar-table .el-calendar-day {
  text-align: center;
}
.custom-calendar >>> .el-calendar-table td {
  border: none;
}
.custom-calendar >>> .el-calendar-table td.is-selected {
  border-radius: var(--td-border-radius);
  background-color: var(--system-active-bg-color);
}
.custom-calendar >>> .el-calendar-table .el-calendar-day:hover {
  border-radius: var(--td-border-radius);
  background-color: var(--system-active-bg-color);
}
.calendar-card {
  width: 100%;
  background-color: #ffffff;
  border-radius: var(--card-border-radius);
  overflow: hidden;
}
.calendar-card >>> .el-calendar-day p {
  margin: 0 !important;
}
.calendar-card >>> .dayItem {
  font-size: 12px;
}
.calendar-card >>> .dayCn {
  display: block;
  font-size: 9px;
}
</style>
